﻿
var webServiceUrl = "http://devapp/_vti_bin/lists.asmx";

var asites = new Array();

asites[0] = { Name: "Dev", Url: "http://devapp" };
asites[1] = { Name: "Cybersecurity & Communications", Url: "http://devapp/dev/site1" };
asites[2] = { Name: "Federal Network Resilience", Url: "http://devapp/dev/site2" };

var instructions = new Array();

instructions[0] = { Name: "Manage Groups", Text: "To add the selected user to a group(s), select the user(s) from the 'Available Users' list and click the right-arrow button to move it into the 'Assigned Users'. To remove a user from a group(s), select the user(s) from the 'Assigned Users' list and click the left-arrow button to move it into the 'Available Users'." };
instructions[1] = { Name: "Manage Users", Text: "To add the selected user to a group(s), select the group(s) from the 'Available Groups' list and click the right-arrow button to move it into the 'Assigned Groups'. To remove a user from a group(s), select the group(s) from the 'Assigned Groups' list and click the left-arrow button to move it into the 'Available Groups'." };

$(function () {
    $(document).ready(function () {

        // Set Navigation Tabs
        $('.tabsMenu li a').click(function () { // catch a click on a tabs menu
            $.UserManagement.SetNavigationTabs($(this));
        });

        $.UserManagement.DefineUserDataTable("#userListTable");
        $.UserManagement.DefineGroupsDataTable("#groupListTable");
        $.UserManagement.DefineUserDataTable("#siteCollUserListTable");       
        $.UserManagement.DefineGroupsDataTable("#siteCollGroupListTable");

        $.UserManagement.PopulateDataTable();

        $('#ManageFormDialog').dialog({
            autoOpen: false,
            height: 'auto',
            width: 900,
            modal: true,
            resizable: false
        });

        $('#addGroupForm').dialog({
            title: 'Add New Group',
            autoOpen: false,
            height: 'auto',
            width: 520,
            modal: true,
            resizable: false
        });
    });
});


$.extend({

    UserManagement: {

        SetNavigationTabs: function (obj) {

            $('.tabsMenu li').removeClass('active'); // remove all current instances of active
            obj.parent().addClass('active'); // add the class active to the item you clicked

            if (obj.html() == "Manage User Groups") {
                $('#UserManagementContent').show();
                $('#GroupManagementContent').hide();
                $('#SiteCollGroupManagementContent').hide();
                $('#SiteCollUserManagementContent').hide();
                $.UserManagement.PopulateDataTable();
            }
            if (obj.html() == "Manage Groups") {
                $('#GroupManagementContent').show();
                $('#UserManagementContent').hide();
                $('#SiteCollGroupManagementContent').hide();
                $('#SiteCollUserManagementContent').hide();
                $.UserManagementGroups.PopulateDataTable();
            }
            if (obj.html() == "Manage Site Collection Users") {
                $('#SiteCollUserManagementContent').show();
                $('#UserManagementContent').hide();
                $('#GroupManagementContent').hide();
                $('#SiteCollGroupManagementContent').hide();
                $.UserManagementSiteCollUsers.PopulateDataTable();
            }
            if (obj.html() == "Manage Site Collection Groups") {
                $('#SiteCollGroupManagementContent').show();
                $('#UserManagementContent').hide();
                $('#GroupManagementContent').hide();
                $('#SiteCollUserManagementContent').hide();
                $("#SiteCollGroupManagementMenu").hide();
                $('#siteCollGroupListTable').dataTable().fnClearTable();
                $.UserManagementSiteCollGroups.LoadSiteCollectionsDropDown();
            }
        },

        DefineUserDataTable: function (tableId) {

            $(tableId).dataTable({
                'columns': [
                        { 'title': 'User Name', 'data': "UserName" },
                        { 'title': 'Login Name', 'data': "LoginName" },
                        { 'title': 'E-mail', 'data': "Email" }
                    ],
                'iDisplayLength': 50,
                'bJQueryUI': true,
                'sDom': 'T<"clear"><"H"lfr>t<"F"ip>'
            });
        },

        DefineGroupsDataTable: function (tableId) {

            $(tableId).dataTable({
                'columns': [
                        { 'title': 'Group Name', 'data': "GroupName" },
                        { 'title': 'Description', 'data': "Description", "sWidth": "70%" }
                    ],
                'iDisplayLength': 50,
                'bJQueryUI': true,
                'sDom': 'T<"clear"><"H"lfr>t<"F"ip>',
                'bAutoWidth': false
            });
        },

        PopulateDataTable: function () {

            try {
                $.UserManagement.LoadFormPage();

                // Initialize User(s) Data Table
                var arryUsers = $.UserManagementDA.GetAllUsers();
                var arryUniqueUser = $.UMUtilities.SortUnique(arryUsers, "UserName");
                $('#userListTable').dataTable().fnClearTable();
                var dt = $('#userListTable').DataTable();
                dt.clear().rows.add(arryUsers).draw();

                // Wire up the data table to handle row selection
                // $(document).on('click', '#userListTable tbody tr', onRowClicked);
                $("#userListTable tbody").delegate("tr", "click", function () {
                    var userName = $("td:first", this).text();
                    var loginName = $("td:eq(1)", this).text();
                    $.UserManagement.PopulateFormPage(userName, loginName);
                });
            }
            catch (e) {
                alert(e);
            }
        },

        LoadFormPage: function () {

            var jqxhr = $.get('html/ManageForm.html');
            jqxhr.success(function (data) {

                $('#ManageFormDialog').html(data);

                // on Click event for adding/removing groups - User Management
                $('#btnAddItems').click(function () {
                    $("#ManageFormTable").hide();
                    $("#LoadingImage").show();
                    $.UserManagement.AddGroupsToUser($('#lblEntityUrlName').html());
                    $("#LoadingImage").hide();
                    $("#ManageFormTable").show();
                });

                $('#btnRemoveItems').click(function () {
                    $("#ManageFormTable").hide();
                    $("#LoadingImage").show();
                    $.UserManagement.RemoveGroupsFromUser($('#lblEntityUrlName').html());
                    $("#LoadingImage").hide();
                    $("#ManageFormTable").show();
                });

                $.UserManagement.SetButtonStyle();
                $.UserManagement.SetGlobalClickEvents();
            });

            jqxhr.error(function () {
                alert('Failed to load edit form.');
            });
        },

        SetGlobalClickEvents: function () {

            $('#filterAvailableItems').click(function () {
                $('#filterAvailableItems').val('');
            });

            $('#filterSelectedItems').click(function () {
                $('#filterSelectedItems').val('');
            });

            // Clear list box data on dialog close
            $('#btnCloseDialog').click(function () {
                $.UserManagement.ClearListBoxItems();
                window.parent.jQuery('#ManageFormDialog').dialog('close');
            });
        },

        PopulateFormPage: function (userName, loginName) {

            try {
                var arryUserInfo = $.UserManagementDA.GetUserInfo(loginName);
                $.UserManagement.RefereshGroupLists(loginName);
                var userInfoUrl = $().SPServices.SPGetCurrentSite() + "/_layouts/userdisp.aspx?ID=" + arryUserInfo[0].UserId;

                $('#EntityTypeTitle').text("User Name:");
                $('#lblInstruction').text(instructions[1].Text);
                $('#AvailableListBoxTitle').text("Available Groups");
                $('#AssignedistBoxTitle').text("Selected Groups");
                $('#filterAvailableItems').val('Search for Users');
                $('#filterSelectedItems').val('Search for Users');

                $("#lblEntityName").text(userName);
                $("#lblEntityUrlName").text(loginName);
                $("#lblEntityUrlName").attr("href", userInfoUrl);
                $('#GroupDescription').hide();
                $('#ManageFormDialog').dialog('open');
            }
            catch (e) {
                alert(e);
            }
        },

        RefereshGroupLists: function (loginName) {

            $.UserManagement.ClearListBoxItems();

            var arryAllAvailableGrps = $.UserManagementDA.GetAllGroups();
            var arrySelectedGroups = $.UserManagementDA.GetGroupsByUser(loginName);
            var arryFilteredGrps = $.UserManagement.FilterAvailableGroups(arryAllAvailableGrps, arrySelectedGroups);

            $.UserManagement.PopulateListBox("#lstBxAvailableItems", "GroupName", arryFilteredGrps);
            $.UserManagement.PopulateListBox("#lstBxSelectedItems", "GroupName", arrySelectedGroups);

            $('#lstBxAvailableItems').filterByText($('#filterAvailableItems'), false);
            $('#lstBxSelectedItems').filterByText($('#filterSelectedItems'), false);

            $.UMUtilities.SetListBoxHeight("#lstBxSelectedItems");
            $.UMUtilities.SetListBoxHeight("#lstBxAvailableItems");
        },

        PopulateListBox: function (listBoxID, key, arryList) {

            $.each(arryList, function (val, text) {
                $(listBoxID).append($('<option></option>').val($.UMUtilities.DecodeText(text[key])).text($.UMUtilities.DecodeText(text[key])));
            });
        },

        FilterAvailableUsers: function (arryAllUsers, arrySelectedUsers) {

            $.each(arrySelectedUsers, function (val, text) {
                arryAllUsers = jQuery.grep(arryAllUsers, function (a) {
                    return a.LoginName !== text["LoginName"];
                });
            });

            return arryAllUsers;
        },

        FilterAvailableGroups: function (arryAvailableGroups, arrySelectedGroups) {

            $.each(arrySelectedGroups, function (val, text) {
                arryAvailableGroups = jQuery.grep(arryAvailableGroups, function (a) {
                    return a.GroupName !== text["GroupName"];
                });
            });

            return arryAvailableGroups;
        },

        AddGroupsToUser: function (loginName) {

            if (loginName == null) {
                alert("No user selected.");
                return;
            }

            if ($("#lstBxAvailableItems").val() == null) {
                alert("You haven't selected any groups to add.");
                return;
            }
            else {
                $('#lstBxAvailableItems option:selected').each(function () {
                    $.UserManagementDA.AddUserToGroup($(this).val(), loginName);
                    $('#lstBxSelectedItems').append($('<option></option>').val($.UMUtilities.DecodeText($(this).val())).text($.UMUtilities.DecodeText($(this).val())));
                });

                $("#lstBxAvailableItems option:selected").remove();
                $.UMUtilities.SetListBoxHeight("#lstBxSelectedItems");
                $.UMUtilities.SetListBoxHeight("#lstBxAvailableItems");
            }
        },

        RemoveGroupsFromUser: function (loginName) {

            if (loginName == null) {
                alert("No user selected.");
                return;
            }

            if ($("#lstBxSelectedItems").val() == null) {
                alert("You haven't selected any groups to remove.");
                return;
            }
            else {
                $('#lstBxSelectedItems option:selected').each(function () {
                    $.UserManagementDA.RemoveUserFromGroup($(this).val(), loginName);
                    $('#lstBxAvailableItems').append($('<option></option>').val($.UMUtilities.DecodeText($(this).val())).text($.UMUtilities.DecodeText($(this).val())));
                });

                $("#lstBxSelectedItems option:selected").remove();
                $.UMUtilities.SetListBoxHeight("#lstBxSelectedItems");
                $.UMUtilities.SetListBoxHeight("#lstBxAvailableItems");
            }
        },

        SetButtonStyle: function () {

            $("#btnCloseDialog").button();
            $("#btnAddItems").button();
            $("#btnRemoveItems").button();
        },

        ClearListBoxItems: function () {

            $('#filterAvailableItems').val('');
            $('#filterSelectedItems').val('');
            $('#lstBxAvailableItems > option').remove();
            $('#lstBxSelectedItems > option').remove();
        }
    }
});